<?php
/**
 * @Author:      ZH
 * @DateTime:    2016-2-16 15:32:48
 * @Description: 用于 pms 采购单
 */
class PMSOrderController extends BaseController {
    /**
     *  列表
     * */
    public function orderList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $page_size = Input::get("page_size",25);
            $page = Input::get("page",1);
            
            $po = PMSOrder::select("*");
            if(Input::get("hope_at_start") != "") $po->where("hope_at",">",Input::get("hope_at_start")." 00:00:00"); //期望日期开始
            if(Input::get("hope_at_end") != "") $po->where("hope_at","<",Input::get("hope_at_end")." 23:59:59");//期望日期结束
            if(Input::get("pms_code") != "") $po->where("pms_code","like",'%'.Input::get("pms_code").'%'); //单号
            if(Input::get("type") != "")$po->where("type",Input::get("type"));//类型  
            if(Input::get("status")!="" ) {$po->where("status",Input::get("status"));}//状态
            if(Input::get("source")!="" ) {$po->where("source",Input::get("source"));}//来源
            $year = Input::get("year") != "" ? Input::get("year") : date("Y");//默认当年
            $po->where("created_at",">","$year-01-01 00:00:00");
            $po->where("created_at","<","$year-12-31 23:59:59");

            $count = $po->count();
            $po = $po->skip($page_size*($page-1))->take($page_size)->orderBy("created_at","DESC")->get();

            if (!empty($po)) {
                foreach ($po as $v) {
                    $v->created_by = PMSUser::created_by_user($v->created_type,$v -> created_by);
                    $v->approve_by = PMSUser::created_by_user($v->approve_type,$v -> approve_by);
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["count"=>$count,"lists"=>$po,'source'=>PMSOrder::$source,'type'=>PMSOrder::$type,'status'=>PMSOrder::$status]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/orderList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     *  订单归属查询
     * */
    public function shopList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $shoplist = MaintenanceShops::select("id","name")->where("status",1)->get();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["shoplist"=>$shoplist]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/shopList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  采购单创建
     * */
    public function createOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'shop_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $shop_id = Input::get("shop_id");
            $shop_info = MaintenanceShops::find($shop_id);
            if ($shop_info->status == 0) {
                $response = Lang::get("pms_error.pms_order_error_40000");
                break;
            }
            
            try{
                DB::beginTransaction();

                 $pms_code = Common::createOrderId(); //'采购单号',
                 $pms_order = new PMSOrder();
                 $pms_order -> pms_code = $pms_code;
                 $pms_order -> source = 2;
                 $pms_order -> created_by = $res['user']->id;
                 $pms_order -> created_type = 2;
                 $pms_order -> shop_id = $shop_id;
                 $pms_order -> status = 1;
                 $pms_order -> type = 1;
                 if (!$pms_order->save())throw new Exception("pms_error.pms_order_create_error_40001");  
                 
                 $pms_order_flow = new PMSOrderFlow();
                 $pms_order_flow -> pms_code = $pms_code;
                 $pms_order_flow -> operation = 1;
                 $pms_order_flow -> status = 1;
                 $pms_order_flow -> created_by = $res['user']->id;
                 $pms_order_flow -> created_type = 2;
                 if (!$pms_order_flow->save()){
                     DB::rollback();
                     throw new Exception("pms_error.pms_order_flow_error_40002");  
                 }
                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }

        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/createOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  采购单详情
     * */
    public function orderInfo(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pms_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $pms_code = Input::get("pms_code");
            $pms_info = PMSOrder::find($pms_code);
            if (empty($pms_info)) {
                $response = Lang::get("pms_error.pms_order_error_40003");
                break;
            }
            $table_c = $pms_info->created_type == 1 ? "SCUser" : "PMSUser" ; //根据用户类型，查询不同的表
            $pms_info->created_by = $table_c::find($pms_info->created_by);
            //'source'=>PMSOrder::$source,'type'=>PMSOrder::$type,'status'=>PMSOrder::$status
            $pms_info->source_name = PMSOrder::$source[$pms_info->source];
            $pms_info->type_name = PMSOrder::$type[$pms_info->type];
            $pms_info->status_name = PMSOrder::$status[$pms_info->status];
            $pms_info->shop = MaintenanceShops::find($pms_info->shop_id);
            
            $product_list = PMSOrderProducts::where('pms_code',$pms_code)->where("status",1)->get();
            if(!empty($product_list)) {
               foreach($product_list as $v){
                   $v -> created_by = PMSUser::created_by_user($v->created_type,$v -> created_by);
                   $v->product_info =  SupplyItem::with(['unit','saleUnit'])->find($v->product_id);
               }
            }
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["pms_info"=>$pms_info,'products'=>$product_list]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/orderInfo", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     *  采购单取消
     * */
    public function delOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pms_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $pms_code = Input::get("pms_code");
            $pms_info = PMSOrder::find($pms_code);
            if (empty($pms_info)) {
                $response = Lang::get("pms_error.pms_order_error_40003");
                break;
            }
            if (!in_array($pms_info->status,[1,3])) { //1新建   3驳回 才能取消
                $response = Lang::get("pms_error.pms_order_status_error_40004");
                break;
            }
            if($pms_info->source != 2){
                $response = Lang::get("pms_error.pms_order_source_error_40007");
                break;
            }
            
            if ($pms_info->type==2) { //1自采不能进行操作
                $response = Lang::get("pms_error.pms_order_type_error_40025");
                break;
            }
            
            try{
                DB::beginTransaction();

                 $pms_info -> status = 0;
                 if (!$pms_info->save())throw new Exception("pms_error.pms_order_create_error_40001");  
                 
                 $up_products = DB::table('pms_order_products')->where('pms_code', $pms_code)->update(array('status' => 0));
                 
                 $pms_order_flow = new PMSOrderFlow();
                 $pms_order_flow -> pms_code = $pms_code;
                 $pms_order_flow -> status = 0;
                 $pms_order_flow -> operation = 0;
                 $pms_order_flow -> created_by = $res['user']->id;
                 $pms_order_flow -> created_type = 2;
                 if (!$pms_order_flow->save()){
                     DB::rollback();
                     throw new Exception("pms_error.pms_order_flow_error_40002");  
                 }

                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }
 
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/delOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     *  采购单商品取消
     * */
    public function delOrderProduct(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_product_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $order_product = PMSOrderProducts::find(Input::get("order_product_id"));
            
            if(empty($order_product)) {
                $response = Lang::get("pms_error.pms_order_product_error_40011");
                break;
            }
            
            $pms_info = PMSOrder::find($order_product->pms_code);
            if (empty($pms_info)) {
                $response = Lang::get("pms_error.pms_order_error_40003");
                break;
            }
            if (!in_array($pms_info->status,[1,3])) { //1新建   3驳回 才能取消
                $response = Lang::get("pms_error.pms_order_status_error_40004");
                break;
            }
            
            try{
                DB::beginTransaction();
                 
                if(!$order_product->delete())throw new Exception("pms_error.pms_order_product_error_40005");
                
                //修改采购单数量
                $pms_info->all_num = $pms_info->all_num - $order_product->all_num;
                if(!$pms_info->save())throw new Exception("pms_error.pms_order_error_40006");

                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }
 
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/delOrderProduct", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  编辑期望收货日期
     * */
    public function editHope(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pms_code' => 'required',
                'hope_at' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $pms_code = Input::get("pms_code");
            $order_info = PMSOrder::find($pms_code);
            if (!in_array($order_info->status,[1,3])) {
                $response = Lang::get("pms_error.pms_order_status_error_40004");
                break;
            }

            $order_info->hope_at = Input::get("hope_at");
            if (!$order_info->save()) {
                $response = Lang::get("pms_error.pms_order_error_40008");
                break;
            }
                        
            $response = array('code' => 0, 'msg' => 'ok', 'result' => []);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/editHope", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    
    /**
     *  商品搜索
     * */
    public function searchProduct(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pms_code' => 'required',
                'key'=> 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $product_list = PMSOrderProducts::pms_products(Input::get("pms_code"));
            foreach ($product_list as $v){
                $p[] = $v->product_id;
            }
            
            $list = SupplyItem::with(['unit'])->select("id","name","code","unit_id","sale_unit_id","volume_size","old_code")->where("retrieval_code","like","%".Input::get('key')."%")
                    ->where("status",1);
            if (!empty($p)) $list -> whereNotIn('id',$p);
            $list = $list->skip(0)->take(100)->get();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["list"=>$list]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/searchProduct", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  采购单商品添加
     * */
    public function addProduct(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pms_code' => 'required',
                'product_id' => 'required',
                'all_num' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $pms_code = Input::get("pms_code");
            $pms_info = PMSOrder::find($pms_code);
            if (empty($pms_info)) {
                $response = Lang::get("pms_error.pms_order_error_40003");
                break;
            }
            if (!in_array($pms_info->status,[1,3])) { //1新建   3驳回 才能添加
                $response = Lang::get("pms_error.pms_order_status_error_40004");
                break;
            }
            
            if ($pms_info->type==2) { //1自采不能进行操作
                $response = Lang::get("pms_error.pms_order_type_error_40025");
                break;
            }
            try{
                DB::beginTransaction();
                 
                $order_product = new PMSOrderProducts();
                $order_product->pms_code = $pms_code;
                $order_product->product_id = Input::get("product_id");
                $order_product->all_num = Input::get("all_num");
                $order_product->created_type = 2; 
                $order_product->created_by = $res['user']->id;
                if(!$order_product->save())throw new Exception("pms_error.pms_order_product_error_40005");
                
                //修改采购单数量
                $pms_info->all_num = $pms_info->all_num + $order_product->all_num;
                if(!$pms_info->save())throw new Exception("pms_error.pms_order_error_40006");
                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }

        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/addProduct", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  采购单提交审核
     * */
    public function approveOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pms_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $pms_code = Input::get("pms_code");
            $pms_info = PMSOrder::find($pms_code);
            if (empty($pms_info)) {
                $response = Lang::get("pms_error.pms_order_error_40003");
                break;
            }
            if (!in_array($pms_info->status,[1,3])) { //1新建  3驳回
                $response = Lang::get("pms_error.pms_order_status_error_40004");
                break;
            }
            
            if ($pms_info->type==2) { //1自采不能进行操作
                $response = Lang::get("pms_error.pms_order_type_error_40025");
                break;
            }
            
            try{
                DB::beginTransaction();

                $pms_info -> status = 2;
                if(!$pms_info->save())throw new Exception("pms_error.pms_order_error_40008");
                
                 $pms_order_flow = new PMSOrderFlow();
                 $pms_order_flow -> pms_code = $pms_code;
                 $pms_order_flow -> status = 2;
                 $pms_order_flow -> operation = 2;
                 $pms_order_flow -> created_by = $res['user']->id;
                 $pms_order_flow -> created_type = 2;
                 if (!$pms_order_flow->save()){
                     DB::rollback();
                     throw new Exception("pms_error.pms_order_flow_error_40002");  
                 }
                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }

        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/approveOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  取消审核
     * */
    public function delApproveOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pms_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $pms_code = Input::get("pms_code");
            $pms_info = PMSOrder::find($pms_code);
            if (empty($pms_info)) {
                $response = Lang::get("pms_error.pms_order_error_40003");
                break;
            }
            if ($pms_info->status != 2) { //2审核中
                $response = Lang::get("pms_error.pms_order_status_error_40004");
                break;
            }
            
            $front = PMSOrderFlow::where('pms_code',$pms_code)->whereIn("status",[1,3])->orderBy("created_at","DESC")->first();
            $front_status = $front->status;
            
            try{
                DB::beginTransaction();

                $pms_info -> status = $front_status;
                if(!$pms_info->save())throw new Exception("pms_error.pms_order_error_40008");
                
                 $pms_order_flow = new PMSOrderFlow();
                 $pms_order_flow -> pms_code = $pms_code;
                 $pms_order_flow -> status = $front_status;
                 $pms_order_flow -> operation = 3;
                 $pms_order_flow -> created_by = $res['user']->id;
                 $pms_order_flow -> created_type = 2;
                 if (!$pms_order_flow->save()){
                     DB::rollback();
                     throw new Exception("pms_error.pms_order_flow_error_40002");  
                 }
                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }

        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/delApproveOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  驳回
     * */
    public function overRuleOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pms_code' => 'required',
                'comment' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $pms_code = Input::get("pms_code");
            $pms_info = PMSOrder::find($pms_code);
            if (empty($pms_info)) {
                $response = Lang::get("pms_error.pms_order_error_40003");
                break;
            }
            if ($pms_info->status != 2) { //2审核中
                $response = Lang::get("pms_error.pms_order_status_error_40004");
                break;
            }
            
            try{
                DB::beginTransaction();

                $pms_info -> status = 3;
                $pms_info -> comment = Input::get("comment");
                if(!$pms_info->save())throw new Exception("pms_error.pms_order_error_40008");
                
                 $pms_order_flow = new PMSOrderFlow();
                 $pms_order_flow -> pms_code = $pms_code;
                 $pms_order_flow -> operation = 4;
                 $pms_order_flow -> status = 3;
                 $pms_order_flow -> comment = Input::get("comment");
                 $pms_order_flow -> created_by = $res['user']->id;
                 $pms_order_flow -> created_type = 2;
                 if (!$pms_order_flow->save()){
                     DB::rollback();
                     throw new Exception("pms_error.pms_order_flow_error_40002");  
                 }
                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }

        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/overRuleOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  反审核
     * */
    public function returnOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pms_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $pms_code = Input::get("pms_code");
            $pms_info = PMSOrder::find($pms_code);
            if (empty($pms_info)) {
                $response = Lang::get("pms_error.pms_order_error_40003");
                break;
            }
            if ($pms_info->status != 4) { //4采购中
                $response = Lang::get("pms_error.pms_order_status_error_40004");
                break;
            }
            
            try{
                DB::beginTransaction();
                
                 $pms_order_flow = new PMSOrderFlow();
                 $pms_order_flow -> pms_code = $pms_code;
                 $pms_order_flow -> operation = 5;
                 $pms_order_flow -> status = 2;
                 $pms_order_flow -> created_by = $res['user']->id;
                 $pms_order_flow -> created_type = 2;
                 if (!$pms_order_flow->save()){
                     DB::rollback();
                     throw new Exception("pms_error.pms_order_flow_error_40002");  
                 }
                 
                $co =  PMSPlanProducts::where("pms_code",$pms_code)->where("plan_code",">",0)->count();
                if ($co > 0 ){              //是否有已经生成订货单的采购项
                    DB::rollback();
                    throw new Exception("pms_error.pms_plan_order_product_error_40010"); 
                } 
                $update = DB::table('pms_order_products')->where('pms_code', $pms_code)->update(array('last_num' => 0));
                
                $del = PMSPlanProducts::where("pms_code",$pms_code)->delete();
                
                $pms_info -> status = 2;
                $pms_info -> last_num = 0;
                if(!$pms_info->save())throw new Exception("pms_error.pms_order_error_40008");
                
                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }

        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/returnOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  审核通过
     * */
    public function okOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pms_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $pms_code = Input::get("pms_code");
            $pms_info = PMSOrder::find($pms_code);
            
            if (empty($pms_info)) {
                $response = Lang::get("pms_error.pms_order_error_40003");
                break;
            }
            if ($pms_info->status != 2) { //2审核中
                $response = Lang::get("pms_error.pms_order_status_error_40004");
                break;
            }
            $shop_info = MaintenanceShops::find($pms_info->shop_id);
            
            try{
                DB::beginTransaction();
                
                 $pms_order_flow = new PMSOrderFlow();
                 $pms_order_flow -> pms_code = $pms_code;
                 $pms_order_flow -> operation = 6;
                 $pms_order_flow -> status = 4;
                 $pms_order_flow -> created_by = $res['user']->id;
                 $pms_order_flow -> created_type = 2;
                 if (!$pms_order_flow->save()){
                     DB::rollback();
                     throw new Exception("pms_error.pms_order_flow_error_40002");  
                 }
                 
                 $last_num = 0;
                $pms_products_info =  PMSOrderProducts::where("pms_code",$pms_code)->where("status",1)->get();
                 foreach($pms_products_info as $v) {
                    $pms_product = PMSOrderProducts::find($v->id);
                    $pms_product -> last_num = $pms_product->all_num;
                    if(!$pms_product->save()){
                        DB::rollback();
                        throw new Exception("pms_error.pms_order_product_error_40005"); 
                    }
                     
                    $plan_products = new PMSPlanProducts();
                    $plan_products->pms_code = $pms_code;
                    $plan_products->product_id = $v->product_id;
                    $plan_products->order_products_id = $v->id;
                    $plan_products->all_num = $v->all_num;
                    $plan_products->from_key = $shop_info->name;
                    if (!$plan_products->save()) {
                        DB::rollback();
                        throw new Exception("pms_error.pms_plan_order_products_error_40009"); 
                    }
                    $last_num += $v->all_num;
                 }
                $pms_info->last_num = $last_num;
                $pms_info->approve_by = $res['user']->id;
                $pms_info->approve_type = 2;
                $pms_info -> status = 4;
                if(!$pms_info->save())throw new Exception("pms_error.pms_order_error_40008");
                 
                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }

        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/okOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     *  订货明细
     * */
    public function planProducts(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pms_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $pms_code = Input::get("pms_code");
            $list = [];
            $plan_products = PMSPlanProducts::where("pms_code",$pms_code)->where('is_split',0)->orderBy("created_at","DESC")->get();
            $order_products_ids = [];
            if (!empty($plan_products)) {
                foreach($plan_products as $v){
                    $order_products_ids[] = $v->order_products_id;
                    $v->product_info =  SupplyItem::with(['unit'])->select("id","name","code","unit_id","sale_unit_id","volume_size","old_code")->find($v->product_id);
                    $v->tax_purchase_price = number_format($v->tax_purchase_price/100,2);
                    $v->no_tax_purchase_price = number_format($v->no_tax_purchase_price/100,2);
                    $plan_info = PMSPlanOrder::select('other_order_code','supplier_id','pay_type')->find($v->plan_code);
                    if (!empty($plan_info)) {
                        $v -> other_order_code = $plan_info -> other_order_code;
                        $v -> pay_type = $plan_info -> pay_type;
                        $v -> supplier_info = MaintenanceSupplier::select("id","name")->find($plan_info -> supplier_id);
                    }else {
                        $v -> other_order_code = "";
                        $v -> supplier_info = "";
                        $v -> pay_type = "";
                    }
                    $list[] = $v;
                }
            }
            
            $order_products = PMSOrderProducts::where("pms_code",$pms_code)->where("status",1)->select("id","product_id")->get();
            if (!empty($order_products)) {
                foreach($order_products as $v){

                    $v->product_info =  SupplyItem::with(['unit'])->select("id","name","code","unit_id","sale_unit_id","volume_size","old_code")->find($v->product_id);
                    $v -> all_num = 0;
                    $v -> last_num = 0;
                    $v -> ready_num = 0;
                    $v -> tax_purchase_price = "0.00";
                    $v -> no_tax_purchase_price = "0.00";
                    $v -> other_order_code = "";
                    $v -> supplier_info = "";
                    $v -> pay_type = "";
                    if (!in_array($v->id,$order_products_ids)) {
                        $list[] = $v;
                    }
                }
            }
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["plan_products"=>$list,"pay_type"=> MaintenanceSupplier::$regular_pay]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/planProducts", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     *  清点明细
     * */
    public function resultProducts(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pms_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $pms_code = Input::get("pms_code");
            
            $result_products = PMSReceiveProductsResult::with(['StorageItem_info'])->where("pms_code",$pms_code)->orderBy("created_at","DESC")->get();
            if (!empty($result_products)) {
                foreach($result_products as $v){
                    $v -> created_by = PMSUser::created_by_user($v->created_type,$v -> created_by);
                    $v->product_info =  SupplyItem::with(['unit'])->select("id","name","code","unit_id","sale_unit_id","volume_size","old_code")->find($v->product_id);
                    $v->data_product_info = SupplyItem::with(['unit'])->select("id","name","code","unit_id","sale_unit_id","volume_size","old_code")->find($v->data_product_id);
                    $receive_products_info = PMSReceiveProducts::find($v->pms_receive_products_id);
                    $v -> tax_purchase_price = $receive_products_info -> tax_purchase_price;
                }
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["result_products"=>$result_products,'type'=>PMSReceiveProductsResult::$type]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/resultProducts", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * 流转明细
     * */
    public function statusOrderList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pms_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $pms_code = Input::get("pms_code");
            
            $status = PMSOrderFlow::where("pms_code",$pms_code)->orderBy("created_at","DESC")->get();
            if(!empty($status)) {
               foreach($status as $v){
                   $v -> created_by = PMSUser::created_by_user($v->created_type,$v -> created_by);
               }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["status_list"=>$status,'operation_name'=>PMSOrderFlow::$operation,'status_name'=>PMSOrderFlow::$status]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/statusOrderList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * 采购单汇总
     * */
    public function groupProduct(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $list = PMSPlanProducts::leftJoin("pms_plan_order","pms_plan_order.plan_code","=","pms_plan_products.plan_code")->leftJoin("pms_order","pms_order.pms_code","=","pms_plan_products.pms_code")->leftJoin("supply_item","supply_item.id","=","pms_plan_products.product_id")->leftJoin("maintenance_supplier","maintenance_supplier.id","=","pms_plan_order.supplier_id")->leftJoin("maintenance_shops","maintenance_shops.id","=","pms_plan_order.shop_id")->leftJoin("anhui_data.supply_unit as bz_unit","bz_unit.id","=","supply_item.unit_id");
            $list->select("pms_plan_order.plan_code as pms_code","pms_plan_order.created_at","maintenance_supplier.id as supplier_id","maintenance_supplier.name as supplier_name","maintenance_shops.id as shop_id","maintenance_shops.name as shop_name","supply_item.name","supply_item.code","supply_item.brand_name","bz_unit.name as unit_name","pms_plan_products.all_num","pms_plan_products.tax_purchase_price");
            $pms_code = Input::get("pms_code");  //此处根据业务需求，由采购单号，改为订货单号
            if ($pms_code) $list->where("pms_plan_products.plan_code","like","%".$pms_code."%");
            
            $start_date = Input::get("start_date");
            if ($start_date) $list->where("pms_plan_order.created_at",">=",$start_date." 00:00:00");
            
            $end_date = Input::get("end_date");
            if ($end_date) $list->where("pms_plan_order.created_at","<=",$end_date." 23:59:59");
            
            $shop_id = Input::get("shop_id");
            if($shop_id){
                $list->where(function($query) use ($shop_id){
                $query->where('pms_order.shop_id', $shop_id)
                      ->orWhere('pms_plan_order.shop_id', $shop_id);
                });
            }
            $supplier_id = Input::get("supplier_id");
            if ($supplier_id) $list->where("pms_plan_order.supplier_id",$supplier_id);
            
            $name = Input::get("name");
            if ($name) $list->where("supply_item.name","like","%".$name."%");
            
            $code = Input::get("code");
            if ($code) $list->where("supply_item.code","like","%".$code."%");
            
            $page_size = Input::get("page_size",20);
            $page = Input::get("page",1);
            $count = $list->count();
            $list = $list->skip($page_size*($page-1))->take($page_size)->orderBy("created_at","DESC")->get();
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["list"=>$list,"count"=>$count]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/groupProduct", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * 供应商搜索项
     * */
    public function supplierSearch(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $list = MaintenanceSupplier::select("id","name");
            $supplier_str = Input::get("supplier_str");
            if($supplier_str != "") $list->where("name","like","%".$supplier_str."%");
            $list = $list->get();

            $response = array('code' => 0, 'msg' => 'ok', 'result' =>["list"=>$list]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/statusOrderList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * 门店搜索项
     * */
    public function shopSearch(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $list = MaintenanceShops::select("id","name");
            $shop_str = Input::get("shop_str");
            if($shop_str != "") $list->where("name","like","%".$shop_str."%");
            $list = $list->get();

            $response = array('code' => 0, 'msg' => 'ok', 'result' =>["list"=>$list]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "order/statusOrderList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}